<template>
  <div>
    <div class="hd">chatBot 智能助手</div>
    <div class="bd">
      <div class="bot-answer" v-if="initialMessage">
        <div>{{ initialMessage }}</div>
      </div>

      <div class="chat" v-for="(item, index) in conversation" :key="index">
        <div class="chat-question" v-if="item.role === 'user'">
          <div class="text">
            {{ item.content }}
          </div>
        </div>
        <div class="chat-answer" v-if="item.role === 'assistant'">
          <div class="img">
            <img src="@/assets/deepseek.png" alt="">
          </div>
          <div class="content">{{ item.content }}</div>
        </div>
      </div>
    </div>

    <div class="ft">
      <div class="input">
        <van-field class="input-msg" v-model="question" placeholder="请输入你的问题" @keyup.enter="onEnterPressed" />
        <van-loading v-if="isLoading" type="spinner" color="#1989fa" />
        <i @click="update" v-else class="iconfont icon-fasong"></i>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = new useRoute()
const conversation = ref([])
const question = ref("")
const isLoading = ref(false)
const content = ref("") // 存储AI回复的内容
const initialMessage = ref("您好！我是您的 AI 智能助手。我可以帮助您解答问题。请问有什么我可以帮您的吗？")

// conversation.value = [
//   { role: 'user', content: `是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的 Enter 和 Esc 会执行 confirm 和` },
//   { role: 'assistant', content: '是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的' },
//   { role: 'user', content: `是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的 Enter 和 Esc 会执行 confirm 和` },
//   { role: 'assistant', content: '是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的' },
//   { role: 'user', content: `是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的 Enter 和 Esc 会执行 confirm 和` },
//   { role: 'assistant', content: '是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的' },
//   { role: 'user', content: `是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的 Enter 和 Esc 会执行 confirm 和` },
//   { role: 'assistant', content: '是否启用键盘能力在展示确认和取消按钮的时候默认情况下键盘的' }
// ]


const update = async () => {
  if (question.value.trim() === "") return
  isLoading.value = true; // 开始加载
  const questionTemp = question.value
  // 添加用户的问题
  conversation.value.push({ role: 'user', content: question.value })
  // 添加用户提问前，先为AI的回复创建一个占位符
  const assistantPlaceholderIndex = conversation.value.length
  conversation.value.push({ role: 'assistant', content: '' })

  scrollToBottom() // 滚动到最底部

  const endpoint = 'https://api.deepseek.com/chat/completions'
  const headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer sk-662f46fa3ed24f0bb17f391af374b79b"
  }

  try {
    const response = await fetch(endpoint, {
      method: "POST",
      headers,
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: [{ role: 'user', content: question.value }],
        stream: true,
      })
    })

    if (response.body) {
      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let done = false
      let buffer = ''

      while (!done) {
        const { value, done: doneReading } = await reader.read()
        done = doneReading
        const chunkValue = buffer + decoder.decode(value)
        buffer = ''
        const lines = chunkValue.split('\n').filter(line => line.startsWith('data: ') && line !== 'data: [DONE]')

        for (const line of lines) {
          const incoming = line.slice(6)
          try {
            const data = JSON.parse(incoming)
            const delta = data.choices[0].delta?.content || ''
            if (delta) {
              // 更新占位符中的内容
              conversation.value[assistantPlaceholderIndex].content += delta
              scrollToBottom() // 滚动到最底部
            }
          } catch (error) {
            console.error('解析错误:', error)
            buffer += incoming
          }
        }
      }
    } else {
      const data = await response.json()
      conversation.value[assistantPlaceholderIndex].content = data.choices[0].message.content
    }
  } catch (error) {
    console.error('请求失败:', error)
    conversation.value[assistantPlaceholderIndex].content = '请求失败，请稍后再试...'
  } finally {
    isLoading.value = false; // 结束加载
  }

  question.value = '' // 清空输入框
}

const scrollToBottom = () => {
  nextTick(() => {
    const container = document.querySelector('.bd')
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}
const checkScroll = () => {
  const inputElement = document.querySelector('.input-msg')
  if (inputElement) {
    const inputHeight = inputElement.scrollHeight
    const containerHeight = inputElement.clientHeight
    if (inputHeight > containerHeight) {
      scrollToBottom()
    }
  }
}

onMounted(() => {
  const { cookName } = route.query
  if (cookName) {
    question.value = `我想要做一道${cookName}`
    update()
  }


  const inputElement = document.querySelector('.input-msg')
  if (inputElement) {
    inputElement.addEventListener('input', checkScroll)
  }
})

const onEnterPressed = () => {
  if (!isLoading.value) { // 确保在加载时不响应回车键
    update();
  }
}
</script>

<style lang="less" scoped>
.hd {
  height: 50px;
  font-size: 0.514rem;
  line-height: 50px;
  background-color: #fff;
  padding-left: 16px;
  position: sticky;
  top: 0;
  z-index: 998;
}

.bd {
  height: calc(100vh - 160px); // 假设头部和底部总共有101px的高度，这里使用视窗单位vh减去这些固定部分的高度
  overflow-y: auto; // 当内容超过容器高度时显示滚动条

  .bot-answer {
    margin-top: 8px;
    margin: 8px 12px 0 12px;
    font-size: 0.4rem;
    line-height: 0.514rem;
  }

  /* background-color: pink; */
  .chat {
    display: flex;
    flex-direction: column;

    &-question {
      margin: 8px 0;

      .text {
        padding: 6px;
        font-size: 0.4rem;
        border-radius: 6px;
        background-color: rgb(232, 234, 236);
        max-width: 7.5rem;
        line-height: 1.4;
        word-wrap: break-word;
        white-space: pre-wrap;
        display: inline-block;
        float: right; // 靠右浮动
        clear: both; // 确保不受之前浮动元素影响
        margin-left: auto; // 让文本块整体右对齐
        margin-right: 12px; // 可选：调整右边距
      }
    }

    &-answer {
      display: flex;

      .img {
        margin-left: 4px;
        width: 35px;
        height: 35px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .content {
        flex: 1;
        margin: 0 8px;
        padding: 6px;
        border-radius: 6px;
        background-color: rgba(159, 172, 230, 0.45);
        font-size: 0.4rem;
        line-height: 24px;
      }
    }
  }
}

.ft {
  position: fixed;
  bottom: 51px;
  height: 50px;
  width: 9.5rem;
  margin: 0 8px;

  .input {
    display: flex;
    align-items: center;
    height: 50px;
    width: 100%;
    background-color: #fff;
    box-shadow:
      0 6px 16px rgba(0, 0, 0, 0.2), // 主要阴影
      0 8px 24px rgba(0, 0, 0, 0.15); // 次要阴影，增加厚度
    border-radius: 12px;

    &-msg {
      height: 100%;
      flex: 1;
      border-radius: 12px;
    }

    .iconfont {
      font-size: 40px;
      color: rgb(86, 102, 171);
    }
  }
}
</style>